<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>原理实例</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .container>div {
            margin: 5px auto;
            width: 100px;
            height: 100px;
            outline: 1px solid red;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
        <div class="item">5</div>
        <div class="item">6</div>
        <div class="item">7</div>
        <div class="item">8</div>
        <div class="item">9</div>
        <div class="item">10</div>
        <div class="item">11</div>
        <div class="item">12</div>
        <div class="item">13</div>
        <div class="item">14</div>
        <div class="item">15</div>
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
        <div class="item">5</div>
        <div class="item">6</div>
        <div class="item">7</div>
        <div class="item">8</div>
        <div class="item">9</div>
        <div class="item">10</div>
        <div class="item">11</div>
        <div class="item">12</div>
        <div class="item">13</div>
        <div class="item">14</div>
        <div class="item">15</div>
    </div>
    <script>
        //io 为 IntersectionObserver对象 - 由IntersectionObserver()构造器创建
        var io = new IntersectionObserver(entries => {
            //entries 为 IntersectionObserverEntry对像数组

            entries.forEach(item => {
                //item 为 IntersectionObserverEntry对像
                // isIntersecting是一个Boolean值，判断目标元素当前是否可见
                if (item.isIntersecting) {
                    //div 可见时 进行相关操作

                    //target目标元素
                    //innerText可获取或设置指定元素标签内的文本值
                    console.log(item.target.innerText);
                    io.unobserve(item.target); //停止监听该div DOM节点
                }
            });
        }); //不传options参数，默认根元素为浏览器视口

        //找到所有的item标签，将其放到数组中
        const divArr = [...document.querySelectorAll(".item")];
        //const divArr = [...document.querySelectorAll("div")];
        console.log(divArr)
        //将divArr中的每个元素，都交给回调函数io.observe(div)处理
        //observe开始监听
        divArr.forEach(divqq => io.observe(divqq)); // 遍历监听所有div DOM节点
    </script>
</body>

</html>